<template>
  <div class="xtx-pagination">
    <a href="javascript:" @click="pageNow--" v-if="pageNow > 1">上一页</a>
    <span v-if="pageInfo.start > 1">...</span>

    <a
      href="javascript:"
      v-for="item in pageInfo.pageButtonArr"
      :key="item"
      :class="{ active: item === pageNow }"
      @click="pageNow = item"
    >
      {{ item }}
    </a>

    <span v-if="pageInfo.end < pages">...</span>
    <a href="javascript:" @click="pageNow++" v-if="pageNow < pages">下一页</a>
  </div>
</template>

<script>
import { computed } from "vue";
import { useVModel } from "@vueuse/core";

export default {
  name: "XtxPagination",
  props: ["pages", "page"],
  setup(props, { emit }) {
    // 页面中显示的页码个数
    const pageButtonNumber = 5;
    // 当前页
    let pageNow = useVModel(props, "page", emit);
    // 获取当前页前面显示的分页按钮的个数
    let leftpageNumber = Math.floor(pageButtonNumber / 2);

    // 计算页码的范围
    let pageInfo = computed(() => {
      // 开始的页数
      let start = pageNow.value - leftpageNumber;
      // 结束的页数
      let end = start + pageButtonNumber - 1;

      // 限制过于点击上一页，负数效果
      if (start < 1) {
        start = 1;
        end = start + pageButtonNumber - 1;
      }

      // 限制过于点击下一页，超出效果
      if (end > props.pages) {
        end = props.pages;
        let temp = end - pageButtonNumber + 1;
        start = temp < 1 ? 1 : temp;
      }

      // 页码数组
      let pageButtonArr = [];
      for (let i = start; i <= end; i++) {
        pageButtonArr.push(i);
      }

      return {
        pageButtonArr,
        start,
        end,
      };
    });

    return {
      pageInfo,
      pageNow,
    };
  },
};
</script>

<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;

  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;

    &:hover {
      color: @xtxColor;
    }

    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }

    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;

      &:hover {
        color: #333;
      }
    }
  }

  > span {
    margin-right: 10px;
  }
}
</style>
